package com.lpc.multiitemtest;

import android.content.Context;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.DisplayMetrics;
import android.view.GestureDetector;
import android.view.MotionEvent;
import android.view.View;
import android.view.WindowManager;
import android.widget.TextView;
import android.widget.Toast;

import com.freelib.multiitem.adapter.BaseItemAdapter;
import com.freelib.multiitem.adapter.holder.BaseViewHolder;
import com.freelib.multiitem.adapter.holder.BaseViewHolderManager;
import com.freelib.multiitem.helper.ItemDragHelper;
import com.freelib.multiitem.item.UniqueItemManager;
import com.freelib.multiitem.listener.OnItemDragListener;
import com.freelib.multiitem.listener.OnItemLongClickListener;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * 功能:
 * <p>
 * 描述:
 * <p>
 * Created by lipc0113 on 2018/7/24.
 */
public class SecondActivity extends AppCompatActivity {

    public static final int NONE = -1;
    private RecyclerView horizontalRecycler;
    private BaseItemAdapter adapter;
    private ItemDragHelper dragHelper;
    //    private ViewScaleHelper scaleHelper;
    protected View contentView;
    private int screenWidth;

    private int currentIndex = 0;
    private int startX;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_panel);

        WindowManager wm = (WindowManager) this.getSystemService(Context.WINDOW_SERVICE);
        DisplayMetrics dm = new DisplayMetrics();
        wm.getDefaultDisplay().getMetrics(dm);
        screenWidth = dm.widthPixels;

        initView();
    }

    private void initView() {

        setTitle("跨表格拖拽");

        contentView = findViewById(R.id.panel_content);

        horizontalRecycler = findViewById(R.id.recyclerView);

        adapter = new BaseItemAdapter();
        //此处为了简单所以使用不可复用的模式，正式业务视具体情况而定！！！
        adapter.addDataItems(Arrays.asList(new UniqueItemManager(
                        new RecyclerViewManager(11)),
                new UniqueItemManager(new RecyclerViewManager(12)),
                new UniqueItemManager(new RecyclerViewManager(3))));
        //设置横向滚动LinearLayoutManager
        horizontalRecycler.setLayoutManager(new LinearLayoutManager(this
                , LinearLayoutManager.HORIZONTAL, false));
        horizontalRecycler.setAdapter(adapter);

        //ItemDragHelper，需要传入外层的横向滚动的RecyclerView
        dragHelper = new ItemDragHelper(horizontalRecycler);
        dragHelper.setOnItemDragListener(new OnBaseDragListener());

//        scaleHelper = new ViewScaleHelper();
        //设置最外层的Content视图
//        scaleHelper.setContentView(contentView);
        //设置横向的Recycler列表视图
//        scaleHelper.setHorizontalView(horizontalRecycler);

        //监听横向滚动RecyclerView双击事件，并开启关闭缩放模式
//        doubleTapToggleScale();
    }

    private void doubleTapToggleScale() {

        final GestureDetector doubleTapGesture = new GestureDetector(this,
                new GestureDetector.SimpleOnGestureListener() {
                    @Override
                    public boolean onDoubleTap(MotionEvent e) {
//                        scaleHelper.toggleScaleModel();
                        return super.onDoubleTap(e);
                    }
                });

        horizontalRecycler.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View view, MotionEvent motionEvent) {
                return doubleTapGesture.onTouchEvent(motionEvent);
            }
        });
    }

    @Override
    public boolean dispatchTouchEvent(MotionEvent ev) {
        //需要把touch事件传给dragHelper，true表示消耗掉事件
        //需要保证在Activity或者外层的ViewGroup或可以拦截Touch事件的地方回调都可以

        if (ev.getActionMasked() == MotionEvent.ACTION_DOWN) {

            startX = (int) ev.getRawX();
        }

        if (dragHelper.onTouch(ev)) {

            touchCoumputer(ev, horizontalRecycler);
            return true;
        }

        //无拖动时，自动复页
        if (ev.getActionMasked() == MotionEvent.ACTION_UP ||
                ev.getActionMasked() == MotionEvent.ACTION_CANCEL ||
                ev.getActionMasked() == MotionEvent.ACTION_OUTSIDE) {

            int scrollX = (int) ev.getRawX() - startX;

            indexComputer(scrollX);
            return true;

        } else {

            return super.dispatchTouchEvent(ev);
        }

//
    }

    private boolean touchCoumputer(MotionEvent ev, RecyclerView recyclerView) {

        if (ev.getActionMasked() == MotionEvent.ACTION_UP ||
                ev.getActionMasked() == MotionEvent.ACTION_CANCEL ||
                ev.getActionMasked() == MotionEvent.ACTION_OUTSIDE) {

            int rawX = getScollYDistance(recyclerView);
            if (0 <= rawX && rawX < screenWidth / 2) {

                recyclerView.smoothScrollToPosition(0);
            } else if (screenWidth / 2 <= rawX && rawX < screenWidth * 3 / 2) {
                recyclerView.smoothScrollToPosition(1);
            } else {
                recyclerView.smoothScrollToPosition(2);
            }

            return true;
        }

        return false;
    }

    private int getScollYDistance(RecyclerView rv) {
        LinearLayoutManager layoutManager = (LinearLayoutManager) rv.getLayoutManager();
        int position = layoutManager.findFirstVisibleItemPosition();
        View firstVisiableChildView = layoutManager.findViewByPosition(position);
        int itemWidth = firstVisiableChildView.getWidth();
        return (position) * itemWidth - firstVisiableChildView.getLeft();
    }

    private void indexComputer(int scrollX) {

        if (scrollX < -screenWidth / 5) {
            currentIndex++;
            if (currentIndex > 2) {
                currentIndex = 2;
            }
        }

        if (scrollX > screenWidth / 5) {
            currentIndex--;
            if (currentIndex < 0) {
                currentIndex = 0;
            }
        }

        horizontalRecycler.smoothScrollToPosition(currentIndex);
    }


    class OnBaseDragListener extends OnItemDragListener {

//        @Override
//        public float getScale() {
//            return scaleHelper.isInScaleMode() ? scaleHelper.getScale() : super.getScale();
//        }

        @Override
        public void onDragFinish(RecyclerView recyclerView, int itemRecyclerPos, int itemPos) {
            super.onDragFinish(recyclerView, itemRecyclerPos, itemPos);
            String text = String.format(
                    "拖动起始第%s个列表的第%s项 结束第%s个列表的第%s项 \n\n拖动数据:%s",
                    originalRecyclerPosition,
                    originalItemPosition,
                    itemRecyclerPos,
                    itemPos,
                    dragItemData);
            Toast.makeText(SecondActivity.this, text, Toast.LENGTH_SHORT).show();
        }
    }

    class RecyclerViewManager extends BaseViewHolderManager<UniqueItemManager> {

        private int length;

        RecyclerViewManager(int length) {
            this.length = length;
        }

        @Override
        protected void onCreateViewHolder(@NonNull BaseViewHolder holder) {
            super.onCreateViewHolder(holder);
            View view = holder.itemView;
            view.getLayoutParams().width = screenWidth;

//            scaleHelper.addVerticalView(view);
            final RecyclerView recyclerView = getView(view, R.id.item_group_recycler);
//            horizontalRecycler.setClipToPadding(false);

            recyclerView.setLayoutManager(new GridLayoutManager(view.getContext(),
                    3,
                    GridLayoutManager.VERTICAL,
                    false));
            final BaseItemAdapter baseItemAdapter = new BaseItemAdapter();
            //为XXBean数据源注册XXHolderManager管理类 数据源必须实现ItemData接口
            baseItemAdapter.register(ImageTextBean.class, new ImageAndTextManager());
            baseItemAdapter.setDataItems(getItemList(length));
            recyclerView.setAdapter(baseItemAdapter);

            baseItemAdapter.setOnItemLongClickListener(new OnItemLongClickListener() {
                @Override
                protected void onItemLongClick(BaseViewHolder viewHolder) {
                    dragHelper.startDrag(viewHolder);
                }
            });
        }

        @Override
        public void onBindViewHolder(@NonNull BaseViewHolder holder, @NonNull UniqueItemManager data) {
            TextView groupTxt = getView(holder.itemView, R.id.index);
            groupTxt.setText(holder.getItemPosition() + "");
        }

        @Override
        protected int getItemLayoutId() {
            return R.layout.item_recycler_view;
        }

        private List<Object> getItemList(int length) {

            List<Object> list = new ArrayList<>();
            for (int i = 0; i < length; i++) {

                //长度大于10的列表的第0个位置不可以被拖动和移动，其他TextDragBean和ImageTextBean的只被禁止不能切换recyclerView
                list.add(new ImageTextBean(R.drawable.img2, "图标" + i));
            }
            return list;
        }

    }
}
